package com.lishangshan.oas_system.controller.process;

import com.lishangshan.oas_system.model.dao.processdao.BursementDao;
import com.lishangshan.oas_system.model.dao.processdao.SubjectDao;
import com.lishangshan.oas_system.model.dao.system.TypeDao;
import com.lishangshan.oas_system.model.dao.user.DeptDao;
import com.lishangshan.oas_system.model.dao.user.PositionDao;
import com.lishangshan.oas_system.model.dao.user.UserDao;
import com.lishangshan.oas_system.model.entity.process.Bursement;
import com.lishangshan.oas_system.model.entity.process.DetailsBurse;
import com.lishangshan.oas_system.model.entity.process.ProcessList;
import com.lishangshan.oas_system.model.entity.process.Subject;
import com.lishangshan.oas_system.model.entity.system.SystemTypeList;
import com.lishangshan.oas_system.model.entity.user.Dept;
import com.lishangshan.oas_system.model.entity.user.Position;
import com.lishangshan.oas_system.model.entity.user.User;
import com.lishangshan.oas_system.service.process.ProcessService;
import com.lishangshan.oas_system.utils.ParameterUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * 新建 流程
 */
@Controller
@RequestMapping("/")
public class ProcedureController {
    @Autowired
    private UserDao userDao;
    @Autowired
    private TypeDao typeDao;

    /**
     * 新建流程 初始化 页面
     *
     * @return
     */
    @RequestMapping("xinxeng")
    public String index() {
        return "process/procedure";
    }

    @Autowired
    private ProcessService processService;
    @Autowired
    private SubjectDao subjectDao;

    /**
     * 费用表单 初始化
     *
     * @param userId
     * @return
     */
    // burse
    @RequestMapping("/burse")
    public String bursement(Model model, @SessionAttribute("userId") Long userId, HttpServletRequest request,
                            @RequestParam(value = "page", defaultValue = ParameterUtil.PAGE_NUMBER) int page,
                            @RequestParam(value = "size", defaultValue = "10") int size, String baseKey) {
        //查找类型
        List<SystemTypeList> uplist = typeDao.findByTypeModel("aoa_bursement");
        //查找费用科目生成树
        List<Subject> second = subjectDao.findByParentId(1L);
        List<Subject> sublist = subjectDao.findByParentIdNot(1L);
        processService.index6(model, userId, page, size);

        model.addAttribute("second", second);
        model.addAttribute("sublist", sublist);
        model.addAttribute("uplist", uplist);
        return "process/bursement";
    }

    @Autowired
    private DeptDao deptDao;
    @Autowired
    private PositionDao positionDao;

    /**
     * 分页操作,搜索操作
     *
     * @param page
     * @param model
     * @param userId
     * @return
     */
    @RequestMapping("/names")
    public String names(@RequestParam(value = "page", defaultValue = ParameterUtil.PAGE_NUMBER) int page,
                        Model model, @SessionAttribute("userId") Long userId, @RequestParam(value = "baseKey", defaultValue = "-1") String baseKey) {
        Pageable pa = new PageRequest(page, ParameterUtil.PAGE_SIZE_MAX);
        if ("-1".equals(baseKey) || "".equals(baseKey.trim())) {
            processService.index6(model, userId, page, ParameterUtil.PAGE_SIZE_MAX);
        } else {
            Page<User> byrealNameLike = userDao.findbyUserNameLike(baseKey, pa);
            model.addAttribute("page", byrealNameLike);
            model.addAttribute("emplist", byrealNameLike.getContent());
            // 查询部门表
            Iterable<Dept> deptlist = deptDao.findAll();
            // 查职位表
            Iterable<Position> poslist = positionDao.findAll();
            model.addAttribute("poslist", poslist);
            model.addAttribute("url", "names");
            model.addAttribute("deptlist", deptlist);
        }
        return "common/recivers";
    }

    @Autowired
    private BursementDao bursementDao;

    /**
     * 添加 费用报销单
     *
     * @return
     * @throws IOException
     * @throws IllegalStateException
     */
    @RequestMapping("apply")
    public String apply(@RequestParam("filePath") MultipartFile filePath, HttpServletRequest req, @Valid Bursement bu, BindingResult br,
                        @SessionAttribute("userId") Long userId) throws IllegalStateException, IOException {
        User lu = userDao.findOne(userId);//申请人
        User reuser = userDao.findByUserName(bu.getUsername());//审核人
        User zhuti = userDao.findByUserName(bu.getNamemoney());//证明人
        Integer allinvoice = 0;
        Double allmoney = 0.0;
        Long roleid = lu.getRole().getRoleId();//申请人角色id
        Long fatherid = lu.getFatherId();//申请人父id
        Long userid = reuser.getUserId();//审核人userid

        String val = req.getParameter("val");

        if (roleid >= 3L && Objects.equals(fatherid, userid)) {


            List<DetailsBurse> mm = bu.getDetails();
            for (DetailsBurse detailsBurse : mm) {
                allinvoice += detailsBurse.getInvoices();
                allmoney += detailsBurse.getDetailmoney();
                detailsBurse.setBurs(bu);
            }
            //在报销费用表里面set票据总数和总金额
            bu.setAllinvoices(allinvoice);
            bu.setAllMoney(allmoney);
            bu.setUsermoney(zhuti);
            //set主表
            ProcessList pro = bu.getProId();
            processService.index5(pro, val, lu, filePath, reuser.getUserName());
            bursementDao.save(bu);

            //存审核表
            processService.index7(reuser, pro);
        } else {
            return "common/proce";
        }
        return "redirect:/xinxeng";
    }
}
